package com.baomidou.springboot.config.mybatis;

import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import org.apache.commons.lang3.ClassUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ConversionServiceFactoryBean;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by kevin on 2018/7/31.
 */
@Configuration
public class MybatisPlusAutoConfiguration {

    /**
     * 将自定义的converter注册到ConversionService中
     *
     * @return
     */
    @Bean
    public ConversionService conversionService() {
        ConversionServiceFactoryBean bean = new ConversionServiceFactoryBean();
        Set<Converter> converters = new HashSet<>();
        converters.add(new String2SqlInjectorConverter());
        bean.setConverters(converters);
        bean.afterPropertiesSet();
        return bean.getObject();
    }

    /**
     * 将String 转成 ISqlInjector 实例
     */
    public class String2SqlInjectorConverter implements Converter<String, ISqlInjector> {
        @Override
        public ISqlInjector convert(String s) {
            if (StringUtils.isEmpty(s))
                return null;

            try {
                Class clazz = ClassUtils.getClass(s);
                ISqlInjector sqlInjector = (ISqlInjector) clazz.newInstance();
                return sqlInjector;
            } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
                ReflectionUtils.rethrowRuntimeException(e);
            }

            return null;
        }
    }
}
